package com.ttg.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ttg.contants.TestContants;
import com.ttg.contants.UrlContants;
import com.ttg.pojo.PayResultPojo;
import com.ttg.security.EncryptionUtils;
import com.ttg.service.PayResultService;
import com.ttg.utils.IdGenerator;
import com.ttg.utils.connection.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/pay_result")
public class PayResultDemoController {

    private static final Logger logger = LoggerFactory.getLogger(PayResultDemoController.class);

    @Autowired
    private PayResultService payResultService;
    @RequestMapping
    public String testPayResult(Model model){
        PayResultPojo payResultPojo = new PayResultPojo();
        payResultPojo.setMerOrderId(IdGenerator.genOrdId16());
        model.addAttribute("payResult",payResultPojo);
        return "demo/pay_result_demo" ;
    }

    @RequestMapping(value = "/do_pay_result",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject doPayResult(PayResultPojo payResultPojo){
        payResultPojo.setMerchantId(TestContants.MERCHANT_ID);
        payResultPojo.setAppId(TestContants.APP_ID);
        payResultPojo.setSignatureAlgorithm(TestContants.SIGNATUREALGORITHM);
        payResultPojo.setSignatureInfo(EncryptionUtils.encryption(payResultPojo.getAllParameters()));
        String resp = HttpClientUtils.sendPostHttpRequest(UrlContants.PAY_RESULT_URL, "POST", payResultPojo.getAllParameters());
        logger.debug("pay result :{}",resp);
        return JSON.parseObject(resp);
    }
}
